package com.yun.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import javax.servlet.Filter;

//启用安全框架
@EnableWebSecurity
@Configuration
//启用@PreAuthorize和@Secured注解
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyLoginTestFilter userService;
    @Autowired
    private QuanXianHanler quanXianHanler;
    @Autowired
    private NoLoginHanler noLoginHanler;
    //设置请求需要的东西
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置跨域
        http.cors(Customizer.withDefaults());
        http.csrf().disable();//关闭跨站请求伪造，否则每次登录需要携带用户名和密码，还有一个随机数
        //代表所有人不需要登录就能访问这个请求
        http.authorizeRequests().antMatchers("/user/login").permitAll();
        //除了登录这个请求以外，其他请求都需要登录才能访问
        http.authorizeRequests().anyRequest().authenticated();
        //设置打完那个出现权限不足异常的时候，使用我们自定义的权限不足异常处理
        http.exceptionHandling().accessDeniedHandler(quanXianHanler);
        http.exceptionHandling().authenticationEntryPoint(noLoginHanler);
        //设置自定义过滤器拦截器的顺序
        http.addFilterBefore(userService, FilterSecurityInterceptor.class);
    }
}
